package com.zys.sac.starter.initializer;

import cn.hutool.core.collection.CollectionUtil;
import com.zys.sac.core.filter.SacCheckFilter;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * sac内部过滤器初始化器，内部会初始化一些过滤器需要的资源
 *
 * @author junekzhong
 * @date 2023/12/12 15:41
 */
public class SacFilterInitializerContext implements ApplicationContextAware, CommandLineRunner, Ordered {

    private ApplicationContext applicationContext;

    public static final Integer ORDER = 10;

    @Override
    public int getOrder() {
        return ORDER;
    }

    @Override
    public void run(String... args) throws Exception {
        Map<String, SacFilterInitializer> initializerBeansMap = applicationContext.getBeansOfType(SacFilterInitializer.class);
        SacCheckFilter filter = applicationContext.getBean(SacCheckFilter.class);
        if (CollectionUtil.isNotEmpty(initializerBeansMap)) {
            Collection<SacFilterInitializer> initializers = initializerBeansMap.values();
            List<SacFilterInitializer> sortedInitializers = initializers.stream().sorted(Comparator.comparing(SacFilterInitializer::getOrder)).collect(Collectors.toList());
            for (SacFilterInitializer initializer : sortedInitializers) {
                initializer.init(filter);
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
